<?php

class XdvertController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array( 
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('index','carousel','ccreate','delete','movie','mcreate','hcarousel','update','hcreate','view','removie','rmcreate','rmupdate'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('index','view','admins','delete','adminCreate','adminUpdate','viewfile'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{ 
        $model=$this->loadModel($id);  
        $model->xdtype =Xdvert::model()->getXdvertType($model->xdtype);

        $title=$model->xdtype;
        $this->render('view',array(
        	'model'=> $model,'title'=> $title,
        ));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionAdminCreate()
	{
		$model=new Xdvert;
 
		if(isset($_POST['Xdvert']))
		{
			$model->attributes=$_POST['Xdvert'];
			$model->xdtype=$_POST['Xdvert']['xdtype'];  
			if($model->xdtype == 0 || $model->xdtype=2){
				//保存上传图片 
			 	$uploadedimage = CUploadedFile::getInstance($model, 'picture');
			 	$datetime=Yii::app()->format->formatDate(time());
	            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
	            if (!file_exists($uploaddir)) {
	                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
	            }
	            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
	                $filename = md5(uniqid());
	                $ext = $uploadedimage->extensionName;
	                $uploadfile = $uploaddir . $filename . '.' . $ext; 
	                $uploadedimage->saveAs($uploadfile);
	                $model->picture = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
	            }
	           }else{
       		 	$model->picture="";
       		 }
			if($model->save())
				$this->redirect(array('admins'));
		}

		$this->render('admincreate',array(
			'model'=>$model,'xdverttype'=>Xdvert::model()->getXdvertType(""),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCcreate()
	{
		$model=new Xdvert;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
         $model->xdtype=0;   
		if(isset($_POST['Xdvert']))
		{
			$model->attributes=$_POST['Xdvert']; 
			$model->xdtype=$_POST['Xdvert']['xdtype'];   

			//保存上传图片 
		 	$uploadedimage = CUploadedFile::getInstance($model, 'picture');
		 	$datetime=Yii::app()->format->formatDate(time());
            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
            }
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext; 
                $uploadedimage->saveAs($uploadfile);
                $model->picture = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
            } 

			if($model->save())
				$this->redirect(array('carousel','show'=>'1'));
		}

		$this->render('create',array(
			'model'=>$model,'xdverttype'=>Xdvert::model()->getXdvertType(""),'title'=>'轮播图广告','filetype'=>"图片大小:640*1136",
		));
	}
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionMcreate()
    {
        $model=new Xdvert;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model); 
         $model->xdtype=1;   
        if(isset($_POST['Xdvert']))
        {
            $model->attributes=$_POST['Xdvert']; 
            $model->xdtype=$_POST['Xdvert']['xdtype'];  

            $model->picture=""; 

            if($model->save())
                $this->redirect(array('movie','show'=>'1'));
        }

        $this->render('create',array(
            'model'=>$model,'xdverttype'=>Xdvert::model()->getXdvertType(""),'title'=>'视频广告','filetype'=>"",
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionRmcreate()
    {
        $model=new Xdvert;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model); 
         $model->xdtype=3;   
        if(isset($_POST['Xdvert']))
        {
            $model->attributes=$_POST['Xdvert']; 
            $model->xdtype=$_POST['Xdvert']['xdtype'];  

            $model->picture=""; 
             //保存上传图片 
            $uploadedimage = CUploadedFile::getInstance($model, 'thumbnails');
            $datetime=Yii::app()->format->formatDate(time());
            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
            }
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext; 
                $uploadedimage->saveAs($uploadfile);
                $model->thumbnails = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
            }
            if($model->save())
                $this->redirect(array('removie','show'=>'1'));
        }

        $this->render('rmcreate',array(
            'model'=>$model,'xdverttype'=>Xdvert::model()->getXdvertType(""),'title'=>'推荐视频','filetype'=>"图片大小:420*294",
        ));
    }
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionHcreate()
    {
        $model=new Xdvert;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
         $model->xdtype=2;   
        if(isset($_POST['Xdvert']))
        {
            $model->attributes=$_POST['Xdvert']; 
            $model->xdtype=$_POST['Xdvert']['xdtype'];   

            //保存上传图片 
            $uploadedimage = CUploadedFile::getInstance($model, 'picture');
            $datetime=Yii::app()->format->formatDate(time());
            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
            }
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext; 
                $uploadedimage->saveAs($uploadfile);
                $model->picture = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
            }

            if($model->save())
                $this->redirect(array('hcarousel','show'=>'1'));
        }

        $this->render('create',array(
            'model'=>$model,'xdverttype'=>Xdvert::model()->getXdvertType(""),'title'=>'门户轮播滚广告','filetype'=>"图片大小:304*198",
        ));
    }

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionAdminUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Xdvert']))
		{

			$oldpictureUrl = dirname(Yii::app()->basePath).$model->picture;
			
			$model->attributes=$_POST['Xdvert'];
			$model->xdtype=$_POST['Xdvert']['xdtype'];   
			if($model->xdtype == 0 || $model->xdtype == 2){
					//更新上传文件
				$uploadedimage = CUploadedFile::getInstance($model, 'picture');
			 	$datetime=Yii::app()->format->formatDate(time());
	            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
	            if (!file_exists($uploaddir)) {
	                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
	            }
	            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
	                $filename = md5(uniqid());
	                $ext = $uploadedimage->extensionName;
	                $uploadfile = $uploaddir . $filename . '.' . $ext; 
	                $uploadedimage->saveAs($uploadfile);
	                $model->picture = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
	                //判断是否旧的logo，如果存在并删除就文件
	                if(file_exists($oldpictureUrl)){
	                	unlink($oldpictureUrl);
	                }
	            }
             }else{
       		 	$model->picture=$_POST['Xdvert']['picture'];
       		 }
			if($model->save())
				$this->redirect(array('admins','id'=>$model->id));
		}

		$this->render('adminupdate',array(
			'model'=>$model,'xdverttype'=>Xdvert::model()->getXdvertType(""),
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Xdvert']))
		{

			$oldpictureUrl = dirname(Yii::app()->basePath).$model->picture;
			$oldpicture = $model->picture; 
			$model->attributes=$_POST['Xdvert']; 
			if($model->xdtype == 0 || $model->xdtype == 2){ 

				//更新上传文件
				$uploadedimage = CUploadedFile::getInstance($model, 'picture');
			 	$datetime=Yii::app()->format->formatDate(time());
	            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
	            if (!file_exists($uploaddir)) {
	                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
	            }
	            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
	                $filename = md5(uniqid());
	                $ext = $uploadedimage->extensionName;
	                $uploadfile = $uploaddir . $filename . '.' . $ext; 
	                $uploadedimage->saveAs($uploadfile);
	                $model->picture = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
	                //判断是否旧的logo，如果存在并删除就文件
	                if(file_exists($oldpictureUrl)){
	                	unlink($oldpictureUrl);
	                }
	            }
            }else{
       		 	$model->picture=$oldpicture ;
       		 }
			if($model->save()){
                if($model->xdtype==0){
                   $this->redirect(array('carousel','show'=>'1'));
                }else if($model->xdtype==1){
                     $this->redirect(array('movie','show'=>'1'));
                }else{
                    $this->redirect(array('hcarousel','show'=>'1'));
                } 
            }
				
		} 
        if($model->xdtype==0){
            $title='轮播图广告';
            $filetype="图片大小:640*1136";
        }else if($model->xdtype==1){
            $title='视频广告';
            $filetype="";
        }else{
            $title='门户轮播图';
            $filetype="图片大小:304*198";
        }

		$this->render('update',array(
			'model'=>$model,'xdverttype'=>Xdvert::model()->getXdvertType(""),'title'=>$title,'filetype'=>$filetype,
		));
	}

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionRmupdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Xdvert']))
        {

            $oldthumbnails = $model->thumbnails; 
            $model->attributes=$_POST['Xdvert'];   

              //保存上传图片 
            $uploadedimage = CUploadedFile::getInstance($model, 'thumbnails'); 
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $datetime=Yii::app()->format->formatDate(time());
                $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
                if (!file_exists($uploaddir)) {
                    mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
                }
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext; 
                $uploadedimage->saveAs($uploadfile);
                $model->thumbnails = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
                 //判断是否旧的logo，如果存在并删除就文件
                if(!empty($oldthumbnails)&&file_exists(dirname(Yii::app()->basePath).$oldthumbnails)){
                    unlink($oldthumbnails);
                }
            }
            if($model->save()){
                $this->redirect(array('removie','show'=>'1'));
                
            }
                
        } 
        
        $title='推荐视频';
        $filetype="图片大小:420*294"; 
        
        $this->render('rmupdate',array(
            'model'=>$model,'xdverttype'=>Xdvert::model()->getXdvertType(""),'title'=>$title,'filetype'=>$filetype,
        ));
    }
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{

		$model=$this->loadModel($id);
		$oldpictureUrl = dirname(Yii::app()->basePath).$model->picture;
		$model->delete(); 

		 if(file_exists($oldpictureUrl)){
            unlink($oldpictureUrl);
         }

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		// $dataProvider=new CActiveDataProvider('Xdvert');
		// $this->render('index',array(
		// 	'dataProvider'=>$dataProvider,
		// ));
		$this->redirect(array('admin'));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmins()
	{ 
		$model=new Xdvert('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Xdvert']))
			$model->attributes=$_GET['Xdvert']; 
		$this->render('admins',array(
			'model'=>$model,
		));
	}

	/**
	 * 管理图片轮播图
	 */
	public function actionCarousel()
	{ 
		$model=new Xdvert('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Xdvert']))
			$model->attributes=$_GET['Xdvert'];
 
		   $model->companyid=Yii::app()->user->id; 
           $model->xdtype=0;

		$this->render('admin',array(
			'model'=>$model,'title'=>'轮播图广告','url'=>'ccreate',
		));
	}

    /**
     * 管理推荐视频
     */
    public function actionRemovie()
    { 
        $model=new Xdvert('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Xdvert']))
            $model->attributes=$_GET['Xdvert'];
 
           $model->companyid=Yii::app()->user->id; 
           $model->xdtype=3;

        $this->render('admin',array(
            'model'=>$model,'title'=>'推荐视频','url'=>'rmcreate',
        ));
    }

    /**
     * 管理视频
     */
    public function actionMovie()
    { 
        $model=new Xdvert('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Xdvert']))
            $model->attributes=$_GET['Xdvert'];
 
           $model->companyid=Yii::app()->user->id; 
           $model->xdtype=1;

        $this->render('admin',array(
            'model'=>$model,'title'=>'视频广告','url'=>'mcreate',
        ));
    }

     /**
     * 门户首页轮播图
     */
    public function actionHcarousel()
    { 
        $model=new Xdvert('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Xdvert']))
            $model->attributes=$_GET['Xdvert'];
 
           $model->companyid=Yii::app()->user->id; 
           $model->xdtype=2;

        $this->render('admin',array(
            'model'=>$model,'title'=>'门户轮播滚广告','url'=>'hcreate',
        ));
    }
 /**
     * undocumented function
     *
     * @return void
     * @author 
     **/
    public function actionViewfile()
    {
        $basepath= dirname(Yii::app()->BasePath);
        $path = $basepath.'/uploads/companyvideo';
       
        $model=$this->traverse($path,$basepath); 
        $returnhtml ='<div id="videoview-grid" class="grid-view">
                    <table class="itemsinfo">
                    <thead><tr>
                    <th id="video-grid_c0">序号</th><th id="video-grid_c1">类型</th><th id="video-grid_c2">文件名</th><th id="video-grid_c3">文件大小</th><th class="button-column" id="video-grid_c4">操作</th></tr>
                    </thead>
                    <tbody>';
            foreach ($model as $key => $value) {
                $viewhtml='';
                if(($key % 2) ==0){
                    $viewhtml.='<tr class="odd">';
                }else{
                    $viewhtml.='<tr class="even">';
                }
                $viewhtml.=' <td width="40px" style="text-align:center">'.($key+1).'</td>';
                $viewhtml.=' <td>'.$value['filetype'].'</td>';
                $viewhtml.=' <td>'.$value['name'].'</td>';
                $viewhtml.=' <td width="80px" style="text-align:center">'.$value['size'].'</td>';//"'.$value['filepath'].'","'.$value['size'].'"
                $viewhtml.=' <td class="button-column"><a class="delete" title="删除" href="javascript:callbacks(\''.$value['filepath'].'\');$.colorbox.close();"><img src="'.Yii::app()->request->baseUrl.'/images/admin/xuanz.png" alt="关联文件"></a></td>';
                $viewhtml.=' </tr>'; 
                $returnhtml.=$viewhtml;
            }
               
             $returnhtml .='</tbody></table> </div>';
             echo $returnhtml ;
    }
     /**
     * 得到文件夹下面所有文件 
     **/
    private function traverse($path,$basepath)
    { 
      $files=array();
      $current_dir = opendir($path);    //opendir()返回一个目录句柄,失败返回false 
      while(($file = readdir($current_dir)) !== false) {    //readdir()返回打开目录句柄中的一个条目
           $sub_dir = $path . DIRECTORY_SEPARATOR . $file;    //构建子目录路径 
             if($file == '.' || $file == '..'|| $file == '.DS_Store'|| $file == 'README.txt' || $file == '._README.txt') {
                   continue;
              } else if(is_dir($sub_dir)) {    //如果是目录,进行递归
                  //echo 'Directory ' . $file . ':<br>';
                  $files=array_merge($files,$this->traverse($sub_dir,$basepath));
                  // $this->traverse($sub_dir,$files);
              } else {    //如果是文件,直接输出
                 $filearray['name']= $file;
                 $filearray['size']= round(filesize($path.'/'.$file)/(1024*1024),2);
                 $path_parts = pathinfo($path.'/'.$file);
                 $filearray['filetype']= $path_parts['extension']; 
                 $filearray['filepath']=str_replace($basepath,'',$path).'/'.$file;
                 //echo '====' . $path . ': ' . $file . ': '.round(filesize($path.'/'.$file)/(1024*1024),2).'MB<br>';
                 $files[] = $filearray;
              } 
        } 
        return $files;
 
    }
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Xdvert the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Xdvert::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Xdvert $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='xdvert-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
